
//  ESTFollowModeViewController.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/19.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "ESTFollowModeViewController.h"
#import "ESTPickerTipView.h"
#import "ESTActivityModel.h"
#import "ESTActivityCustomerInfoTableViewCell.h"
#import "ESTActivityDetailViewController.h"
#import "ESTActivitySearchViewController.h"
#import "ESTFollowUpRecordViewController.h"
#import "TYZIndicatorView.h"

#define FollowUp_CollectionViewItemID               @"FollowUp_CollectionViewItemID"
#define FollowUp_CollectionViewLableFont            CoreInfo.fontSize * 0.8
#define FollowUp_CollectionViewLableHeightPadding   15
#define FollowUp_CollectionViewLableWidthPadding    20
#define FollowUp_ActivityNumberTip_Height           40
#define FollowUp_PartPadding_Height                 5

@interface ESTFollowModeViewController ()<UITableViewDelegate, UITableViewDataSource>
/**
 *  TableView
 */
@property(nonatomic, strong) TYZTableView *tableView;
/**
 *  数据源
 */
@property(nonatomic, strong) NSMutableArray<ESTCustomerInfoModel *> *modelArray;
/**
 *  所有的活动
 */
@property(nonatomic, strong) NSArray<ESTActivityModel *> *activityData;
/**
 *  选择了第几个
 */
@property(nonatomic, assign) NSInteger activityInteger;
/**
 *  刷新请求的页码
 */
@property(nonatomic, assign) NSInteger page_num;
/**
 *  选择标签的字符串
 */
@property(nonatomic, copy) NSString *selectedLabelString;
/**
 *  总共多少个数据
 */
@property(nonatomic, assign) NSInteger dataNumber;
/**
 *  是否删除了TableView
 */
@property(nonatomic, assign) BOOL isNoData;
/**
 *  第几种排序
 */
@property(nonatomic, assign) NSInteger sequenceCount;
/**
 *  排序方式
 YES 降序
 NO  升序
 */
@property(nonatomic, assign) BOOL sequenceMode;
/**
 *  记录偏移量
 */
@property(nonatomic, assign) CGPoint lastContentOffset;
@end

@implementation ESTFollowModeViewController
#pragma mark - 生命周期方法
- (void)viewDidLoad {
    [super viewDidLoad];
    TYZButton *rightButton1 = [[TYZButton alloc] initWithFrame:CGRectMake(7.5, 7.5, 20, 20)];
    TYZButton *rightButton2 = [[TYZButton alloc] initWithFrame:CGRectMake(7.5, 7.5, 20, 20)];
    [rightButton1 setImage:[UIImage imageNamed:@"na_add"] forState:UIControlStateNormal];
    [rightButton2 setImage:[UIImage imageNamed:@"na_search"] forState:UIControlStateNormal];
    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
    UIBarButtonItem *rightItem2 = [[UIBarButtonItem alloc] initWithCustomView:rightButton2];
    [rightButton1 addTarget:self action:@selector(didClickAddButton) forControlEvents:UIControlEventTouchUpInside];
    [rightButton2 addTarget:self action:@selector(didClickSearchButton) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItems = @[rightItem1, rightItem2];
    
    self.sequenceMode = YES;
    self.sequenceCount = 2;
    self.page_num = 1;
    [self setupIndicatorView];
    [self setupActivityPickerView];
    [self acquireActivity];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
#pragma mark - 设置UI
- (void)setupIndicatorView {
    TYZIndicatorModel *model = [[TYZIndicatorModel alloc] init];
    model.font = TYZFont(CoreInfo.fontSize * 0.8);
    TYZIndicatorView *indicator = [TYZIndicatorView indicatorWithTextArray:BaseInfo.againFollowUpLabelArray dataModel:model];
    [self.view addSubview:indicator];
    [indicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(Height_Indicator);
    }];
    WEAKSELF
    [indicator setDidSelectedItemBlock:^(NSArray<TYZSelectedModel *> *modelArray) {
        [weakSelf handleAgainFollowUpLabelsWithSelectedArray:modelArray];
        [weakSelf pullDownRefreshData];
    }];
}
- (void)setupActivityPickerView {
    TYZView *numberView = [self.view viewWithTag:TAG_SIXTH_ACTIVITY_SELECTACTIVITYVIEW];
    if (numberView) {
        [numberView removeFromSuperview];
    }
    numberView = [[TYZView alloc] init];
    [self.view addSubview:numberView];
    numberView.tag = TAG_SIXTH_ACTIVITY_SELECTACTIVITYVIEW;
    [numberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(self.mode == FollowUpMode_Again ? (FollowUp_PartPadding_Height + Height_Indicator) : 0);
        make.height.mas_equalTo(FollowUp_ActivityNumberTip_Height);
    }];
    numberView.backgroundColor = TYZWhiteColor;
    // 总共多少个数据
    TYZLabel *numberLabel = [[TYZLabel alloc] init];
    numberLabel.text =[NSString stringWithFormat:@"共:%ld", (long)self.dataNumber];
    numberLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    [numberView addSubview:numberLabel];
    [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(numberView).offset(-10);
        make.centerY.equalTo(numberView);
    }];
    // 点击的排序图标
    TYZButton *sequenceButton = [TYZButton buttonWithType:UIButtonTypeCustom];
    [numberView addSubview:sequenceButton];
    [sequenceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(numberView);
        make.right.equalTo(numberLabel.mas_left).offset(-10);
        make.height.width.mas_equalTo(20);
    }];
    sequenceButton.transform = self.sequenceMode ? CGAffineTransformMakeRotation(M_PI) : CGAffineTransformMakeRotation(0);
    [sequenceButton setImage:[UIImage imageNamed:@"arrow_sequence"] forState:UIControlStateNormal];
    [sequenceButton addTarget:self action:@selector(didClickSequenceButton:) forControlEvents:UIControlEventTouchUpInside];
    // 排序方式
    ESTPickerTipView *sequencePickerView = [[ESTPickerTipView alloc] init];
    sequencePickerView.title = BaseInfo.sequenceTextArray[self.sequenceCount];
    sequencePickerView.textColor = PickerTipViewTextColor_333;
    sequencePickerView.titleLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    sequencePickerView.dataArray = BaseInfo.sequenceTextArray;
    sequencePickerView.pickerTitle = [@"选择排序方式" S];
    sequencePickerView.selectedValue = @[BaseInfo.sequenceTextArray[self.sequenceCount]];
    [numberView addSubview:sequencePickerView];
    [sequencePickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(numberView);
        make.right.equalTo(sequenceButton.mas_left).offset(-10);
    }];
    WEAKSELF
    [sequencePickerView setDidChooseNumberBlock:^(NSArray<NSNumber *> *numberArray) {
        weakSelf.sequenceCount = [numberArray.lastObject integerValue];
        [weakSelf refreshAllData];
    }];
    // 选择活动
    __block NSString *name = [@"选择活动" S];
    [self.activityData enumerateObjectsUsingBlock:^(ESTActivityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.ACTIVITY_ID isEqualToString:self.activity_id]) {
            name = obj.ACTIVITY_NAME;
            *stop = YES;
        }
    }];
    ESTPickerTipView *activityPickerView = [[ESTPickerTipView alloc] init];
    activityPickerView.title = name;
    activityPickerView.textColor = PickerTipViewTextColor_333;
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:self.activityData.count];
    [self.activityData enumerateObjectsUsingBlock:^(ESTActivityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [arrM addObject:obj.ACTIVITY_NAME];
    }];
    activityPickerView.titleLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    activityPickerView.dataArray = [arrM mutableCopy];
    activityPickerView.pickerTitle = [@"选择活动" S];
    activityPickerView.selectedValue = @[name];
    [numberView addSubview:activityPickerView];
    [activityPickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(numberView);
        make.left.equalTo(numberView).offset(10);
    }];
    [activityPickerView setDidChooseNumberBlock:^(NSArray<NSNumber *> *numberArray) {
        weakSelf.activityInteger = [numberArray.lastObject integerValue];
    }];
}
- (void)setupTableView {
    [self.view addSubview:self.tableView];
    CGFloat padding = self.mode == FollowUpMode_Again ? (FollowUp_PartPadding_Height * 2 + Height_Indicator) : FollowUp_PartPadding_Height;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset(FollowUp_ActivityNumberTip_Height + padding);
    }];
    [self setupTableViewHeader];
}
- (void)setupTableViewHeader {
    WEAKSELF
    self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownRefreshData];
    }];
}
- (void)setupTableViewFooter {
    WEAKSELF
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf pullUpLoadMore];
    }];
}
#pragma mark - actions
- (void)pullDownRefreshData {
    self.page_num = 1;
    [self.modelArray removeAllObjects];
    [self acquireData];
}
- (void)pullUpLoadMore {
    self.page_num++;
    [self acquireData];
}
- (void)refreshAllData {
    [self setupActivityPickerView];
    [self pullDownRefreshData];
}
- (void)refreshTableViewData {
//    self.lastContentOffset = self.tableView.contentOffset;
    [self.tableView reloadData];
//    self.tableView.contentOffset = self.lastContentOffset;
}
- (void)acquireData {
    WEAKSELF
    [TYZLoadingView showMessage:nil];
    [ESTCustomerInfoModel requestFollowUpListDataWithFollowUpMode:self.mode activityID:self.activity_id orderbyType:BaseInfo.sequenceCodeArray[self.sequenceCount] orderbyDesc:self.sequenceMode followUpLabel:self.selectedLabelString page_num:self.page_num success:^(NSArray<ESTCustomerInfoModel *> *modelArray, NSInteger dataNumber) {
        [TYZLoadingView hideHUD];
        [weakSelf handleModelArray:modelArray dataNumber:dataNumber];
        [weakSelf.tableView.mj_header endRefreshing];
    } failure:^(NSString *error) {
        [TYZLoadingView showError:NetworkUnusual];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf handleModelArray:nil dataNumber:0];
    }];
}
- (void)acquireActivity {
    WEAKSELF
    [ESTActivityModel requestAllActivitySuccess:^(NSArray<ESTActivityModel *> *modelArray) {
        weakSelf.activityData = modelArray;
    } failure:^(NSString *error) {
        weakSelf.activityData = nil;
        [TYZLoadingView showError:NetworkUnusual];
    }];
}
#pragma mark - actions
- (void)didClickAddButton {
    ESTFollowUpRecordViewController *controller = [[ESTFollowUpRecordViewController alloc] init];
    controller.followUpType = FollowUpRecordType_Add;
    controller.activity_id = self.activity_id;
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)didClickSearchButton {
    ESTActivitySearchViewController *controller = [[ESTActivitySearchViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)didClickSequenceButton:(TYZButton *)button {
    self.sequenceMode = !self.sequenceMode;
    [self refreshAllData];
}
- (void)handleAgainFollowUpLabelsWithSelectedArray:(NSArray<TYZSelectedModel *> *)selectedArray {
    __block NSString *str = @"";
    [selectedArray enumerateObjectsUsingBlock:^(TYZSelectedModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        str = [NSString stringWithFormat:@"%@,%@", str, obj.name];
    }];
    self.selectedLabelString = str;
}
- (void)handleModelArray:(NSArray<ESTCustomerInfoModel *> *)modelArray dataNumber:(NSInteger)dataNumber {
    if (self.mode == FollowUpMode_Again) {
//        __block NSInteger newNumber = dataNumber;
//        NSMutableArray<ESTCustomerInfoModel *> *arrM = [NSMutableArray arrayWithArray:modelArray];
//        [modelArray enumerateObjectsUsingBlock:^(ESTCustomerInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            if ([obj.IS_PLANCOME isEqualToString:@"1"]) {
//                [arrM removeObject:obj];
//                newNumber--;
//            }
//        }];
//        modelArray = [arrM mutableCopy];
//        dataNumber = newNumber;
    }
    if (self.dataNumber != dataNumber) {
        self.dataNumber = dataNumber;
        [self setupActivityPickerView];
    }
    if (modelArray.count > 0) {
        [self.tableView.mj_footer endRefreshing];
        [self.modelArray addObjectsFromArray:modelArray];
        if (modelArray.count < Request_PageSize_Normal) {
            self.page_num--;
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    if (self.modelArray.count > 0) {
        [self.view removeNoDataImage];
        if (self.isNoData) {
            self.isNoData = NO;
            [self setupTableView];
        } else {
            [self refreshTableViewData];
        }
        if (self.modelArray.count < Request_PageSize_Normal) {
            [self.tableView.mj_footer removeFromSuperview];
        } else {
            if (self.tableView.mj_footer == nil) {
                [self setupTableViewFooter];
            }
        }
    } else {
        self.isNoData = YES;
        [self.tableView removeFromSuperview];
        WEAKSELF
        [self.view noDataWithClick:^{
            [weakSelf pullDownRefreshData];
        }];
    }
}
- (CGFloat)cellHeightWithIndexPath:(NSIndexPath *)indexPath {
    NSArray *arr = [self.modelArray[indexPath.section].FOLLOWUP_LABLE componentsSeparatedByString:@","];
    NSInteger lines = 0;
    if (arr.count > 1) {
        lines = arr.count / 4 + 1;
        if (arr.count % 4 == 0) {
            lines--;
        }
    }
    CGFloat height = 0;
    if (self.mode == FollowUpMode_Again) {
        height = CustomerInfoTableViewCell_FirstPartHeight + lines * ActivityAchieveTableViewCell_LabelBorderHeight + ActivityAchieveTableViewCell_LinePadding + ActivityAchieveTableViewCell_ContentLineHeight * 4;
    } else {
        height = CustomerInfoTableViewCell_FirstPartHeight + (lines + 1) * ActivityAchieveTableViewCell_LabelBorderHeight + ActivityAchieveTableViewCell_LinePadding + ActivityAchieveTableViewCell_ContentLineHeight * 3;
    }
    return height;
}
// 行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.mode == FollowUpMode_First) {
        return CustomerInfoTableViewCell_FirstPartHeight + ActivityAchieveTableViewCell_LinePadding + ActivityAchieveTableViewCell_ContentLineHeight * 4;
    }
    return [self cellHeightWithIndexPath:indexPath];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return Value_Height_PartPadding;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    TYZView *view = [[TYZView alloc] init];
    view.backgroundColor = ESTBackgroundColor;
    return view;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.modelArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ESTActivityCustomerInfoTableViewCell *cell = [ESTActivityCustomerInfoTableViewCell creatActivityCustomerInfoTableViewCell:tableView item:self.mode];
    cell.model = self.modelArray[indexPath.section];
    WEAKSELF
    [cell setDidClickActivityNameBlock:^(NSString *activity_id) {
        ESTActivityDetailViewController *controller = [[ESTActivityDetailViewController alloc] init];
        controller.activity_id = activity_id;
        [weakSelf.navigationController pushViewController:controller animated:YES];
    }];
    __weak typeof(indexPath) weakIndexPath = indexPath;
    [cell setComplementDialBlock:^(NSString *duration) {
        ESTFollowUpRecordViewController *controller = [[ESTFollowUpRecordViewController alloc] init];
        controller.followUpType = FollowUpRecordType_Normal;
        controller.duration = duration;
        controller.followUpType = FollowUpRecordType_Phone;
        controller.model = weakSelf.modelArray[indexPath.section];
        [controller setDidClickPreserveBlock:^(BOOL success) {
            if (success) {
                [weakSelf.modelArray removeObjectAtIndex:weakIndexPath.section];
                [weakSelf.tableView reloadData];
            }
        }];
        [weakSelf.navigationController pushViewController:controller animated:YES];
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ESTFollowUpRecordViewController *controller = [[ESTFollowUpRecordViewController alloc] init];
    controller.followUpType = FollowUpRecordType_Normal;
    controller.firstFollowUp = self.mode == FollowUpMode_First;
    controller.model = self.modelArray[indexPath.section];
    WEAKSELF
    __weak typeof(indexPath) weakIndexPath = indexPath;
    [controller setDidClickPreserveBlock:^(BOOL success) {
        if (success) {
            [weakSelf.modelArray removeObjectAtIndex:weakIndexPath.section];
            [weakSelf.tableView reloadData];
        }
    }];
    [self.navigationController pushViewController:controller animated:YES];
}
#pragma mark - setter & getter
- (void)setMode:(ESTFollowUpMode)mode {
    _mode = mode;
    self.mainTitle = BaseInfo.matterTextArray[mode];
}
- (TYZTableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[TYZTableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (void)setActivityInteger:(NSInteger)activityInteger {
    _activityInteger = activityInteger;
    self.activity_id = self.activityData[self.activityInteger].ACTIVITY_ID;
    [self refreshAllData];
}
- (void)setActivityData:(NSArray<ESTActivityModel *> *)activityData {
    _activityData = activityData;
    [self setupTableView];
    [self refreshAllData];
}
- (NSMutableArray<ESTCustomerInfoModel *> *)modelArray {
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
@end
